package com.morningstone.bamboo.controller;

import com.morningstone.bamboo.pojo.StatisticTradersDO;
import com.morningstone.bamboo.pojo.StatisticTradersToExcelDO;
import com.morningstone.bamboo.utils.DoubleListErgodic;
import com.morningstone.report.core.*;
import com.morningstone.report.utils.AttachmentExportUtil;
import freemarker.template.TemplateModelException;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: OrderController
 * @author: 7lQ
 * @date: 2021/7/30 下午 4:37
 * @Description
 * @since JDK 1.8
 */
@RestController
public class OrderController {
    @Autowired
    private DoubleListErgodic doubleListErgodic;


    @PostMapping("export")
    @ApiOperation(value = "测试", produces = "text/plain;charset=UTF-8")
    public void export(@RequestBody() List<StatisticTradersToExcelDO> statisticTradersToExcelDOS, HttpServletResponse response) throws IOException {
        try (ExcelBuilder excelBuilder = new BeetlExcelBuilder()) {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("data", statisticTradersToExcelDOS);
            dataMap.put("sheetName", "beetl_excel_example");
            Workbook workbook = excelBuilder.useDefaultStyle().template("/templates/贸易商期现版详情列表.btl").build(dataMap);
            AttachmentExportUtil.export(workbook, "beetl_excel", response);
        }

    }

    @PostMapping("/freemarker/example")
    public void build(@RequestBody() List<StatisticTradersToExcelDO> record, HttpServletResponse response) throws IOException {
        try (ExcelBuilder excelBuilder = new FreemarkerExcelBuilder()) {
            Map<String, Object> dataMap = new HashMap<>();
            for (int i = 0; i < record.size(); i++) {
                List<Object> listParam = new ArrayList<>(2);
                listParam.add(record.get(i).getFutureList());
                listParam.add(record.get(i).getSpotInfoList());
                List resultList = (List) doubleListErgodic.exec(listParam);
                record.get(i).setMultiList(resultList);
            }
            dataMap.put("data", record);
            // dataMap.put("sheetName", "beetl_excel_example");
            Workbook workbook = excelBuilder.template("/templates/贸易商期现版详情列表1.ftl").build(dataMap);
            AttachmentExportUtil.export(workbook, "贸易商期现版详情列表", response);
        } catch (TemplateModelException e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/freemarker/qwer")
    public void buildqwer(@RequestBody() List<StatisticTradersToExcelDO> record, HttpServletResponse response) throws IOException {
        try (ExcelBuilder excelBuilder = new FreemarkerExcelBuilder()) {
            Map<String, Object> dataMap = new HashMap<>();
            List<Object> listParam = new ArrayList<>();
            for (int i = 0; i < record.size(); i++) {
                listParam.add(record.get(i).getFutureList());
                listParam.add(record.get(i).getSpotInfoList());
                List resultList = (List) doubleListErgodic.exec(listParam);
                record.get(i).setMultiList(resultList);
            }

            dataMap.put("data", record);
            dataMap.put("sheetName", "beetl_excel_example");
            Workbook workbook = excelBuilder.template("/templates/贸易商期现版详情列表1.ftl").build(dataMap);
            AttachmentExportUtil.export(workbook, "freemarker_excel", response);
        } catch (TemplateModelException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("qwer")
    public HttpServletResponse qwer_(HttpServletResponse response) throws FileNotFoundException {
        try {
            // path是指欲下载的文件的路径。
            File file = new File("D:\\ChenShi\\Project\\StoneReport\\bamboo\\src\\main\\resources\\templates\\新建文本文档.txt");
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream("D:\\ChenShi\\Project\\StoneReport\\bamboo\\src\\main\\resources\\templates\\新建文本文档.txt"));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return response;

    }

    @GetMapping("export1")
    @ApiOperation(value = "测试", produces = "application/octet-stream")
    public void export1(HttpServletResponse response) throws IOException {
        try (ExcelBuilder excelBuilder = new BeetlExcelBuilder()) {
            List<StatisticTradersDO> list = new ArrayList<>();
            StatisticTradersDO statisticTradersDO = new StatisticTradersDO();
            statisticTradersDO.setHedgeNO("1234");
            list.add(statisticTradersDO);
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("data", list);
            dataMap.put("sheetName", "beetl_excel_example");
            Workbook workbook = excelBuilder.template("/templates/1234.btl").build(dataMap);
            AttachmentExportUtil.export(workbook, "beetl_excel", response);
        }
    }

    @GetMapping("/csv")
    @ApiOperation(value = "测试", produces = "application/octet-stream")
    public void csv(StatisticTradersDO statisticTradersDO, HttpServletResponse response) {
        List<StatisticTradersDO> list = new ArrayList<>();
        list.add(statisticTradersDO);
        Csv csv = CsvBuilder.of(StatisticTradersDO.class).build(list);
        AttachmentExportUtil.export(csv.getFilePath(), "123.csv", response);
    }

    @GetMapping("/htmlToExcel/example")
    @ApiOperation(value = "测试", produces = "application/octet-stream")
    public void htmlToExcel(HttpServletResponse response, StatisticTradersDO statisticTradersDO) throws Exception {
        // get html file
        List<StatisticTradersDO> list = new ArrayList<>();
        list.add(statisticTradersDO);
        URL htmlToExcelEampleURL = this.getClass().getResource("/templates/123.html");
        Path path = Paths.get(htmlToExcelEampleURL.toURI());

        // read the html file and use default excel style to create excel
        Workbook workbook = HtmlToExcelFactory.readHtml(path.toFile()).build();

        // this is a example,you can write the workbook to any valid outputstream
        AttachmentExportUtil.export(workbook, "转换示例", response);
    }


    @GetMapping("/csv1")
    @ApiOperation(value = "测试", produces = "application/octet-stream")
    public void csv1(StatisticTradersDO statisticTradersDO, HttpServletResponse response) throws IOException {

        try (ExcelBuilder excelBuilder = new BeetlExcelBuilder()) {
            Map<String, StatisticTradersDO> map = new HashMap<>();
            map.put("data", statisticTradersDO);
            Workbook workbook = excelBuilder
                    .template("/templates/beetlToExcelExample.btl")
                    .workbookType(WorkbookType.XLSX)
                    .useDefaultStyle()
                    .build(map);
            AttachmentExportUtil.export(workbook, "beetl_excel", response);
        }
    }
}
